package com.sunlands.qdcy.tongzhuo.web;

import com.sunlands.qdcy.tongzhuo.common.annotation.AutoLog;
import com.sunlands.qdcy.tongzhuo.constant.CommonResultMessage;
import com.sunlands.qdcy.tongzhuo.exception.SensitiveException;
import com.sunlands.qdcy.tongzhuo.feign.SocketClient;
import com.sunlands.qdcy.tongzhuo.model.DiaryTopicDO;
import com.sunlands.qdcy.tongzhuo.service.UserDiaryTopicService;
import com.sunlands.qdcy.tongzhuo.vo.*;
import io.swagger.annotations.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

import static com.sunlands.qdcy.tongzhuo.common.annotation.AutoLog.Level.DEBUG;
import static com.sunlands.qdcy.tongzhuo.constant.CommonResultMessage.CON_SENSITIVE;

/**
 * @author shixiaopeng
 */

@Slf4j
@Api(tags = "3、话题相关")
@RestController
@RequestMapping("/topic")
public class TopicController extends BaseController {

    @Autowired
    private UserDiaryTopicService userDiaryTopicService;
    @Autowired
    private SocketClient socketClient;

    @AutoLog
    @ApiOperation(value = "保存历史话题")
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/save")
    public BusinessResult<HistoryTopicVO> saveHistoryTopic(@RequestBody HistoryTopicVO historyTopicVO) {
        if (StringUtils.isEmpty(historyTopicVO.getTopic())) {
            throw new IllegalArgumentException("话题不能为空！");
        }
        Long currentUserId = currentUserId();
        if(Objects.isNull(currentUserId)){
            throw new IllegalArgumentException("userId 为空！");
        }
        historyTopicVO.setUserId(currentUserId);
        CheckVO checkVO = CheckVO.builder().content(historyTopicVO.getTopic()).isSpecial(false).build();
        BusinessResult checkContent = socketClient.checkContent(checkVO);
        if (checkContent.getCode().equals(CON_SENSITIVE.code)) {
            throw new SensitiveException("话题内容： " + historyTopicVO.getTopic() + "\n敏感词：" +checkContent.getMessage());
        }
        return BusinessResult.createSuccessInstance(userDiaryTopicService.saveHistoryTopic(historyTopicVO.getUserId().toString(), historyTopicVO.getTopic()));
    }

    @AutoLog
    @ApiOperation(value = "关注/取消关注--话题")
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/attention")
    public BusinessResult attentionTopic(@RequestBody HistoryTopicVO historyTopicVO) {
        DiaryTopicDO diaryTopic = userDiaryTopicService.findDiaryTopic(historyTopicVO.getId());
        String message;
        if(historyTopicVO.getAttention()){
            message = userDiaryTopicService.attentionTopic(historyTopicVO.getUserId().toString(), diaryTopic.getTopic(), historyTopicVO.getId());
        }else{
            message = userDiaryTopicService.cancelAttention(historyTopicVO.getUserId().toString(), diaryTopic.getTopic());
        }
        return BusinessResult.createInstance(CommonResultMessage.SUCCESS.code, message);
    }

    @AutoLog(logLevel = DEBUG)
    @ApiOperation(value = "话题详情")
    @PreAuthorize("isAuthenticated()")
    @PostMapping("/topic_detail")
    public BusinessResult<MyTopicVO> topicDetail(@RequestBody HistoryTopicVO historyTopicVO) {
        DiaryTopicDO diaryTopic = userDiaryTopicService.findDiaryTopic(historyTopicVO.getId());
        historyTopicVO.setTopic(diaryTopic.getTopic());
        return BusinessResult.createSuccessInstance(userDiaryTopicService.topicDetail(historyTopicVO, diaryTopic));
    }

    @AutoLog
    @ApiOperation(value = "我关注的话题列表")
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/attention_list/{userId}")
    public BusinessResult<Page<MyTopicVO>> attentionTopic(@PathVariable("userId") Long userId,
                                                          @ApiParam(value = "页码") @RequestParam(defaultValue = "1") Integer page,
                                                          @ApiParam(value = "页码大小") @RequestParam(defaultValue = "20") Integer pageSize) {

        return BusinessResult.createSuccessInstance(userDiaryTopicService.attentionaTopicList(userId, page, pageSize));
    }

    @AutoLog(logLevel = DEBUG)
    @ApiOperation(value = "查历史话题和推荐话题")
    @PreAuthorize("isAuthenticated()")
    @GetMapping("/history_recommend")
    public BusinessResult<TopicDataDTO> historyRecommend(@ApiParam(value = "用户id") @RequestParam Long userId) {
        List<String> historyTopic = userDiaryTopicService.historyTopic(userId.toString());
        List<RecommendTopicVO> recommendTopicVOS = userDiaryTopicService.recommendTopic("recommend");
        TopicDataDTO data = new TopicDataDTO();
        data.setHistory(historyTopic);
        data.setRecommend(recommendTopicVOS);
        if(historyTopic.size() == 0){
            return BusinessResult.createInstance(CommonResultMessage.SUCCESS.code, "不存在历史话题或者已删除!", data);
        }
        return BusinessResult.createSuccessInstance(data);
    }

    @AutoLog
    @ApiOperation(value = "删除历史话题")
    @PreAuthorize("isAuthenticated()")
    @DeleteMapping("/delete/{userId}")
    public BusinessResult deleteTopic(@PathVariable("userId") Long userId) {
        userDiaryTopicService.deleteHistoryTopic(userId.toString());
        return BusinessResult.createSuccessInstance(null);
    }


    @Data
    @ApiModel(value = "历史话题和推荐话题")
    public static class TopicDataDTO implements Serializable {
        @ApiModelProperty(position = 1, value = "历史话题")
        private List<String> history;

        @ApiModelProperty(position = 2, value = "推荐话题")
        private List<RecommendTopicVO> recommend;
    }
}
